<?php
/**
 * Created by PhpStorm.
 * User: yaoihu
 * Date: 2019/6/16
 * Time: 0:37
 */

namespace DC\BonusCenter\Services;


use DC\BonusCenter\CommonBonus;
use App\Models\Shop\AgentSalesModel;
use Carbon\Carbon;
use DC\UserCenter\Models\UserBaseModel;

class AgentBonus extends CommonBonus
{
    public function award()
    {
        $end = Carbon::today()->timestamp-1;
        $start = Carbon::today()->subDay(1)->timestamp;
        AgentSalesModel::where('agent_type',1)->whereBetween('started_at',[$start,$end])->where('is_settle',0)
            ->selectRaw('ANY_VALUE(id)as id,user_id')
            ->groupBy('user_id')->orderBy('user_id')->chunkById(200,function ($agents) use ($start,$end){
                foreach ($agents as $agent){
                    AgentSalesModel::where('agent_type',1)
                        ->where('user_id',$agent->user_id)
                        ->whereBetween('started_at',[$start,$end])->update(['is_settle'=>1]);
                    $this->tjBonus($agent->user_id);
                }
            });
    }

    public function tjBonus($relate_id)
    {
        $end = Carbon::today()->timestamp-1;
        $start = Carbon::today()->subDay(1)->timestamp;

        $info  = UserBaseModel::where('status','>=',0)->where('member_id',$relate_id)->first();
        if(!$info){
            return false;
        }
        $max_deep = get_rule('tj_max_deep');
        $tids = UserBaseModel::where('status','>=',0)
            ->whereRaw("FIND_IN_SET(`member_id`,?)",[$info->referrer_ids])
            ->where('tdeep','>=',$info->tdeep-$max_deep)->pluck('member_id')->toArray();
        if(!$tids||empty($tids)){
            return false;
        }
        $rule = format_rule(get_rule('tj_award'));
        foreach ($tids as $tid){
            $tinfo = UserBaseModel::find($tid);
            if(!$tinfo){
                continue;
            }

            if(!AgentSalesModel::where('agent_type',1)->whereBetween('started_at',[$start,$end])
                ->where('user_id',$tid)->first()
            ){
                continue;
            }
            $tnum = UserBaseModel::where('referrer_id',$tid)->where('status','>=',0)->count();
            $deep = $info->tdeep-$tinfo->tdeep;

            if($tnum<$deep){
                continue;
            }

            if(isset($rule[$deep])&&!empty($rule[$deep])){
                $bonus = $rule[$deep][1]??0;
                if($bonus&&is_numeric($bonus)){
                    $this->setBonusAllot([['field'=>'money2','rates'=>100,'type'=>1]])
                        ->settleBonus(49,$tid,$relate_id,$bonus,4);
                }
                unset($bonus);
            }
            unset($tnum,$deep,$tinfo);
        }

        return true;
    }

}